package picturetaker.application;

import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.net.URLConnection;
import java.util.concurrent.BlockingQueue;


import picturetaker.utility.ApplicationConstants;
import picturetaker.domain.Camera;
import picturetaker.domain.PicData;
import picturetaker.domain.Picture;

public class CameraThread implements Runnable, ApplicationConstants {

	private BlockingQueue<Picture> queue = null;

	private Camera cam = null;

	private Object lock = null;

	private boolean running = true;

	public CameraThread(Camera cam, BlockingQueue<Picture> queue, Object lock) {
		this.cam = cam;
		this.queue = queue;
		this.lock = lock;
	}

	public void run() {
		synchronized (lock) {
			try {lock.wait();} catch (InterruptedException e) {}
		}
		BufferedInputStream in = null;
		ByteArrayOutputStream out = null;
		
		
		int readBytes = 0;
		byte[] pic = null;
		while (running) {
			try {
				try {
					URLConnection urlConn = cam.getCameraUrl().openConnection();
					urlConn.setRequestProperty(AUTHORI_PROPERTY, ENCRYPTION
							+ cam.getEncryptedLogin());
					urlConn.connect();

					in = new BufferedInputStream (urlConn.getInputStream());
					out = new ByteArrayOutputStream();
					
					do {
						readBytes = in.read();
						out.write(readBytes);
					} while (readBytes >= 0);
					out.flush();
					
					
					//Security encrypter = new Security();
					//encrypter.EnCryptDES (in , out);
					
					
					pic = out.toByteArray();
					queue.put(new Picture(cam.getCameraName(),
							cam, new PicData(pic)));
					out.close();
					in.close();
				} catch (IOException e) {
					// Ignore
				}
				synchronized (lock) {
					lock.wait();
				}				
			} catch (InterruptedException e) {
				// Ignore
			}
		}
	}


	public boolean isRunning() {
		return running;
	}

	public void setRunning(boolean running) {
		this.running = running;
	}

	public Object getLock() {
		return lock;
	}

	public void setLock(Object lock) {
		this.lock = lock;
	}
}
